package com.lhkj.ct.quartz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lhkj.ct.base.exception.job.TaskException;
import com.lhkj.ct.base.model.dto.PageQuery;
import com.lhkj.ct.quartz.common.enums.JobGroup;
import com.lhkj.ct.quartz.mapper.TblJobMapper;
import com.lhkj.ct.quartz.model.entity.TblJob;
import com.lhkj.ct.quartz.service.QuartzJobService;
import com.lhkj.ct.quartz.util.ScheduleConstants;
import com.lhkj.ct.quartz.util.ScheduleUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobDataMap;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 定时任务调度表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2023-09-19
 */
@Service
public class QuartzJobServiceImpl implements QuartzJobService {

    @Resource
    private Scheduler scheduler;

    @Resource
    private TblJobMapper jobMapper;

    /**
     * 项目启动时，初始化定时器 主要是防止手动修改数据库导致未同步到定时任务处理（注：不能手动修改数据库ID和任务组名，否则会导致脏数据）
     */
    @PostConstruct
    public void init() throws SchedulerException, TaskException {
        scheduler.clear();
        List<TblJob> jobList = jobMapper.selectList(new QueryWrapper<>());
        for (TblJob job : jobList) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
    }

    /**
     * 获取quartz调度器的计划任务定时任务分页
     */
    @Override
    public IPage<TblJob> selectJobPage(TblJob job, PageQuery pageQuery) {
        LambdaQueryWrapper<TblJob> queryWrapper = new LambdaQueryWrapper<TblJob>()
                .like(StringUtils.isNotBlank(job.getJobName()), TblJob::getJobName, job.getJobName());
        return jobMapper.selectPage(generatePage(pageQuery), queryWrapper);
    }

    @Override
    public TblJob selectById(String jobId) {
        return jobMapper.selectById(jobId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertJob(TblJob job) throws SchedulerException, TaskException {
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = jobMapper.insert(job);
        if (rows > 0) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateJob(TblJob job) throws SchedulerException, TaskException {
        TblJob properties = this.selectById(job.getId());
        int rows = jobMapper.updateById(job);
        if (rows > 0) {
            updateSchedulerJob(job, properties.getJobGroup());
        }
        return rows;
    }

    /**
     * 任务调度状态修改
     *
     * @param job 调度信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int changeStatus(TblJob job) throws SchedulerException {
        int rows = 0;
        String status = job.getStatus();
        if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) {
            rows = resumeJob(job);
        } else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) {
            rows = pauseJob(job);
        }
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean run(TblJob job) throws SchedulerException {
        boolean result = false;
        TblJob properties = this.selectById(job.getId());
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties);
        JobKey jobKey = ScheduleUtils.getJobKey(job.getId(), job.getJobGroup());
        if (scheduler.checkExists(jobKey)) {
            result = true;
            scheduler.triggerJob(jobKey, dataMap);
        }
        return result;
    }

    /**
     * 暂停任务
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int pauseJob(TblJob job) throws SchedulerException {
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = jobMapper.updateById(job);
        if (rows > 0) {
            scheduler.pauseJob(ScheduleUtils.getJobKey( job.getId(),  job.getJobGroup()));
        }
        return rows;
    }

    /**
     * 恢复任务
     *
     * @param job 调度信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int resumeJob(TblJob job) throws SchedulerException {
        job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
        int rows = jobMapper.updateById(job);
        if (rows > 0) {
            scheduler.resumeJob(ScheduleUtils.getJobKey(job.getId(), job.getJobGroup()));
        }
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteJob(TblJob job) throws SchedulerException {
        int rows = jobMapper.deleteById(job.getId());
        if (rows > 0) {
            scheduler.deleteJob(ScheduleUtils.getJobKey(job.getId(), job.getJobGroup()));
        }
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteJobByIds(List<String> jobIds) throws SchedulerException {
        for (String jobId : jobIds) {
            TblJob job = this.selectById(jobId);
            if (null == job) {
                continue;
            }
            deleteJob(job);
        }
    }

    /**
     * 更新任务
     *
     * @param job 任务对象
     * @param jobGroup 任务组名
     */
    public void updateSchedulerJob(TblJob job, JobGroup jobGroup) throws SchedulerException, TaskException {
        // 判断是否存在
        JobKey jobKey = ScheduleUtils.getJobKey(job.getId(), jobGroup);
        if (scheduler.checkExists(jobKey)) {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(jobKey);
        }
        ScheduleUtils.createScheduleJob(scheduler, job);
    }
}
